//
//  WHPhotoBrowserCell.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/12/2.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

//    MARK: - 代理协议
protocol WHYPhotoBrowserCellDelegate: NSObjectProtocol {
    /// 图片被点击
    func photoBrowserCellShouldDismiss()
    
    /// 图片被缩放
    ///
    /// - parameter scale: 缩放比例
    func photoBrowserCellDidZoom(scale: CGFloat)
}

class WHYPhotoBrowserCell: UICollectionViewCell {
    
//    MARK: - 代理
    weak var delegate: WHYPhotoBrowserCellDelegate?
    
//    MARK: - 监听方法
    @objc private func tapImage() {
        delegate?.photoBrowserCellShouldDismiss()
    }
    
//    MARK: - 加载数据
    var imageURL: NSURL? {
        didSet {
            
            guard let url = imageURL else {
                return
            }
            
            resetScrollView()
            
            let key = url.absoluteString
            
            let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            setupPlaceHolderImageView(placeHolderImage)
            
            imageView.sd_setImageWithURL(middleURL(url),
                placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in
                    
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeHolderImageView.progress = CGFloat(current) / CGFloat(total)
                    })
                    
                }) { (image, error, _, _) -> Void in
                
                guard let img = image else {
                    SVProgressHUD.showErrorWithStatus("加载图片失败")
                    return
                }
                
                self.placeHolderImageView.hidden = true
                    
                self.setupImagePosition(img)
            }
        }
    }
    
//    MARK: - 设置占位图片
    /// 设置占位图片
    ///
    /// - parameter image: 占位图片 -- 必须为可选，要不当图片加载失败会崩溃
    private func setupPlaceHolderImageView (image: UIImage?) {
        
        placeHolderImageView.hidden = false
        
        placeHolderImageView.image = image
        
        placeHolderImageView.sizeToFit()
        
        placeHolderImageView.center = scrollView.center
        
    }
    
//    MARK: - 重置scrollView
    private func resetScrollView() {
//        重设形变参数
        imageView.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentSize = CGSizeZero
        scrollView.contentOffset = CGPointZero
        
    }
    
//    MARK: - 设置图片位置
    /// 设置图片位置
    ///
    /// - parameter image: 要显示的图片
    private func setupImagePosition(image: UIImage) {
        
        let size = displaySize(image)
        scrollView.contentSize = size
        
        if size.height > scrollView.bounds.height {
            imageView.frame = CGRect(origin: CGPointZero, size: size)
        }else {
            imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            
            let y = (scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
        }
        
    }
    
//    MARK: - 计算图片显示大小
    /// 计算图片显示大小
    ///
    /// - parameter image: 要显示的图片
    ///
    /// - returns: 图片大小
    private func displaySize(image: UIImage) -> CGSize {
        let w = scrollView.bounds.width
        let h = w * image.size.height / image.size.width
        
        return CGSize(width: w, height: h)
    }
    
//    MARK: - 返回中图URL
    /// 返回中图URL
    ///
    /// - parameter url: 小图地址
    ///
    /// - returns: 返回中图地址
    private func middleURL(url: NSURL) -> NSURL {
        
        var urlString = url.absoluteString
        
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        
        return NSURL(string: urlString)!
    }
    
//    MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - 懒加载子控件
    private lazy var placeHolderImageView: WHYProgressImageView = WHYProgressImageView()
    
    lazy var scrollView: UIScrollView = UIScrollView()
    
    lazy var imageView: UIImageView = UIImageView()
    
}

//    MARK: - 设置UI
extension WHYPhotoBrowserCell {
    
    private func setupUI () {
        
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageView)
        scrollView.addSubview(placeHolderImageView)
        
        var rect = bounds
        rect.size.width -= 20//让scrollView的宽度比cell的宽度少20
        scrollView.frame = rect
        
        prepareScrollView()
        
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageView.userInteractionEnabled = true
        imageView.addGestureRecognizer(tap)
    }
    
    private func prepareScrollView() {
        
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        
    }
    
}

// MARK: - UIScrollViewDelegate
extension WHYPhotoBrowserCell: UIScrollViewDelegate {
    
//    返回要缩放的控件
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    /// 缩放完成后调用
    ///
    /// - parameter scrollView: 当前滚动视图
    /// - parameter view:       被缩放的视图
    /// - parameter scale:      缩放完成的比例
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        if scale < 1.0 {
            delegate?.photoBrowserCellShouldDismiss()
            imageView.hidden = true
            return
        }
        
//        此处不能用view.bounds,因为缩放、平移、旋转不会改变view.bounds的值，
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
//        QL2(scrollView.bounds.width)
//        QL2(view!.bounds.width)
        
        offsetY = offsetY < 0 ? 0 : offsetY
        offsetX = offsetX < 0 ? 0 : offsetX
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
    }
    
//    只要缩放就会调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        delegate?.photoBrowserCellDidZoom(imageView.transform.a)
    }
    
}




